<template>
  <div class="product-list-container">
    <!-- 商品表格 -->
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" label-width="80px">
          <el-form-item label="产品名称">
            <el-input v-model="searchForm.gName" placeholder="请输入产品名称" clearable />
          </el-form-item>
          <el-form-item label="产品种类">
            <el-select v-model="searchForm.gCategoryId" placeholder="请选择种类" clearable style="width: 150px">
              <el-option
                v-for="category in categoryOptions"
                :key="category.value"
                :label="category.label"
                :value="category.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="是否热销">
            <el-select v-model="searchForm.gHot" placeholder="请选择热销状态" clearable style="width: 150px">
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增商品</el-button>
        <el-button type="success" @click="handleEditSelected">修改商品</el-button>
        <el-button
          type="danger"
          :disabled="selectedRows.length === 0"
          @click="handleDeleteSelected"
        >
          批量删除({{ selectedRows.length }})
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
        :data="goodList"
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
      >
        <!-- 复选框列 -->
        <el-table-column type="selection" width="55" align="center"></el-table-column>

        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="gImage" label="商品图片" width="100" align="center">
          <template #default="{ row }">
            <img
              :src="row.gImage"
              alt="商品图片"
              style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;"
            />
          </template>
        </el-table-column>
        <el-table-column prop="gName" label="商品名称" min-width="150" />

        <el-table-column prop="gPrice" label="价格" width="100" align="center">
          <template #default="{ row }">
            ￥{{ row.gPrice }}
          </template>
        </el-table-column>

        <el-table-column prop="gNumber" label="库存" width="100" align="center" />

        <el-table-column prop="gStatus" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.gStatus ? 'success' : 'danger'" size="small">
              {{ row.gStatus ? '上架中' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="gHot" label="热销" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.gHot ? 'warning' : null" size="small">
              {{ row.gHot ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="gCreateTime" label="创建时间" width="170" align="center" />

        <el-table-column label="操作" width="150" align="center">
          <template #default="{ $index, row }">
            <el-button size="small" type="primary" link @click="openEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(row, $index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑商品弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="isEditing ? '编辑商品' : '新增商品'" width="500px">
      <el-form :model="editForm" :rules="addRules" ref="editFormRef" label-width="100px">
        <el-form-item label="商品名称" prop="gName">
          <el-input v-model="editForm.gName" />
        </el-form-item>
        <el-form-item label="商品图片" prop="gImage">
          <el-input v-model="editForm.gImage" />
        </el-form-item>
        <el-form-item label="价格" prop="gPrice">
          <el-input-number v-model="editForm.gPrice" :precision="2" :step="0.1" style="width: 100%" />
        </el-form-item>
        <el-form-item label="商品分类" prop="gCategoryId">
          <el-select v-model="editForm.gCategoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="category in categoryOptions"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态" prop="gStatus">
          <el-select v-model="editForm.gStatus" placeholder="请选择状态" style="width: 100%">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量" prop="gNumber">
          <el-input-number v-model="editForm.gNumber" style="width: 100%" />
        </el-form-item>
        <el-form-item label="商品描述" prop="gDesciption">
          <el-input v-model="editForm.gDesciption" type="textarea" :rows="3" style="width: 100%" />
        </el-form-item>
        <el-form-item label="是否热销" prop="gHot">
          <el-switch v-model="editForm.gHot" active-value="1" inactive-value="0" />
        </el-form-item>
        <el-form-item label="标签名称" prop="typenames">
          <el-select v-model="editForm.typenames" multiple placeholder="请选择标签" style="width: 100%">
            <el-option
              v-for="tag in tagOptions"
              :key="tag.value"
              :label="tag.label"
              :value="tag.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import goodApi from '@/api/controller'

export default {
  data() {
    return {
      goodList: [],
      total: 0,
      currentPage: 1,
      pageSize: 5,
      searchForm: {
        gName: null,
        gCategoryId: null,
        gHot: null
      },
      selectedRows: [], // 存储选中的行

      // 标签选项（动态）
      tagOptions: [],

      // 商品分类选项（动态）
      categoryOptions: [],

      // 编辑相关数据
      editDialogVisible: false,
      isEditing: false,
      editForm: {
        id: null,
        gName: '',
        gImage: '',
        gPrice: 0,
        gCategoryId: null,
        gStatus: 1,
        gNumber: 0,
        gDesciption: '',
        gHot: 0,
        typenames: []
      },
      addRules: {
        gName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        gPrice: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        gCategoryId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
        gNumber: [{ required: true, message: '请输入库存数量', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getGoodListPage()
    this.fetchTags()
    this.fetchCategories()
  },
  methods: {
    async getGoodListPage(page = 1) {
      try {
        const res = await goodApi.getGoodListPage(
          page,
          this.pageSize,
          this.searchForm.gName,
          this.searchForm.gCategoryId,
          this.searchForm.gHot
        )
        if (res && res.code === 200) {
          this.goodList = res.rows
          this.total = res.total
          this.currentPage = page
        } else {
          this.$message.error('获取商品列表失败')
        }
      } catch (error) {
        console.error(error)
        this.$message.error('请求失败，请检查网络')
      }
    },

    handlePageChange(page) {
      this.currentPage = page
      this.getGoodListPage(page)
    },

    handleSelectionChange(rows) {
      this.selectedRows = rows
    },

    handleAdd() {
      this.isEditing = false
      this.editForm = {
        id: null,
        gName: '',
        gImage: '',
        gPrice: 0,
        gCategoryId: null,
        gStatus: 1,
        gNumber: 0,
        gDesciption: '',
        gHot: 0,
        typenames: []
      }
      this.editDialogVisible = true
    },

    async openEditDialog(row) {
  if (!row || !row.id) {
    this.$message.warning('无法编辑该商品：数据不完整');
    return;
  }

  try {
    const res = await goodApi.getTypeById(row.id);

    let typeNames = [];
    if (res.data && Array.isArray(res.data)) {
      typeNames = res.data.map(tag => {
        if (typeof tag === 'string') {
          const matchedTag = this.tagOptions.find(t => t.label === tag);
          return matchedTag ? matchedTag.value : null;
        }
        return tag;
      }).filter(Boolean);
    }

    this.editForm = {
      ...row,
      gStatus: row.gStatus ? 1 : 0,
      typenames: typeNames
    };

    this.isEditing = true;
    this.editDialogVisible = true;
  } catch (error) {
    console.error('获取商品详情失败:', error);
    this.$message.warning('无法加载商品详情，请稍后再试');
  }
},

    async fetchTags() {
      try {
        const res = await goodApi.getType()
        if (res && res.code === 200) {
          this.tagOptions = res.data.map(tag => ({
            label: tag.tName,
            value: tag.tId
          }))
        } else {
          this.$message.error('获取标签失败')
        }
      } catch (error) {
        console.error('获取标签失败:', error)
        this.$message.error('网络异常，请稍后再试')
      }
    },

    async fetchCategories() {
      try {
        const res = await goodApi.getCategoryList()
        if (res && res.code === 200) {
          this.categoryOptions = res.data.map(category => ({
            label: category.cName,
            value: category.cId
          }))
        } else {
          this.$message.error('获取分类失败')
        }
      } catch (error) {
        console.error('获取分类失败:', error)
        this.$message.error('网络异常，请稍后再试')
      }
    },

    submitEditForm() {
  this.$refs.editFormRef.validate(async valid => {
    if (valid) {
      const payload = { ...this.editForm }
      const currentUser = this.$store.getters.getUserInfo?.username || '未知用户'
      payload.gStatus = Number(payload.gStatus)
      payload.gHot = Number(payload.gHot)
      payload.gPrice = parseFloat(payload.gPrice.toFixed(2)) 


      if (Array.isArray(payload.typenames)) {
    
        payload.typeName = payload.typenames.map(id => {
          const tag = this.tagOptions.find(t => t.value === id)
          return tag ? tag.label : null
        }).filter(Boolean)
      }

      delete payload.typenames

      // 设置创建人和更新人字段
      if (!this.isEditing) {
        payload.gCreateUser = currentUser
      }
      payload.gUpdateUser = currentUser

      try {
        let res
        if (this.isEditing) {
          res = await goodApi.updateGood(payload)
        } else {
          // 使用正确的插入接口
          res = await goodApi.addGood(payload)
        }
        
        if (res && res.code === 200) {
          this.$message.success(this.isEditing ? '更新成功' : '新增成功')
          this.editDialogVisible = false
          this.getGoodListPage(this.currentPage)
        } else {
          this.$message.error(res.message || this.isEditing ? '更新失败' : '新增失败')
        }
      } catch (error) {
        console.error(this.isEditing ? '更新失败:' : '新增失败:', error)
        this.$message.error('网络异常，请稍后再试')
      }
    } else {
      return false
    }
  })
},

    async deleteGoods(ids) {
      try {
        const res = await goodApi.deleteGoodsByIds(ids)
        if (res && res.code === 200) {
          this.$message.success('删除成功')
          this.getGoodListPage(this.currentPage)
        } else {
          this.$message.error(res.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('网络异常，请稍后再试')
      }
    },

    async handleDelete(row) {
      try {
        const confirmResult = await this.$confirm('确定要删除该商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        if (confirmResult === 'confirm') {
          await this.deleteGoods([row.id])
        }
      } catch (error) {
        this.$message.info('已取消删除'+error)
      }
    },

    async handleDeleteSelected() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一行')
        return
      }

      try {
        const confirmResult = await this.$confirm('确定要删除选中的商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        if (confirmResult === 'confirm') {
          const ids = this.selectedRows.map(row => row.id)
          await this.deleteGoods(ids)
        }
      } catch (error) {
        this.$message.error('操作失败，请稍后再试'+error)
      }
    },

    handleEditSelected() {
      if (this.selectedRows.length !== 1) {
        this.$message.warning('请选择一行进行编辑')
        return
      }
      const row = this.selectedRows[0]
      this.openEditDialog(row)
    },

    handleSearch() {
      this.getGoodListPage(1)
    }
  }
}
</script>

<style scoped>
.product-list-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.search-bar {
  margin-bottom: 20px;
}
</style>